package com.abigoni.ciaomondoandroid.bflows.activity;

import java.sql.SQLException;

import com.abigoni.ciaomondoandroid.R;
import com.abigoni.ciaomondoandroid.bflows.helper.MyDbHelper;
import com.abigoni.ciaomondoandroid.blogics.user.User;
import com.abigoni.ciaomondoandroid.blogics.user.UserService;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {

	public EditText user;
	public EditText pwd;
	public MyDbHelper myDbHelper;
	private SQLiteDatabase db;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		myDbHelper = new MyDbHelper(MainActivity.this);
		db         = this.myDbHelper.getReadableDatabase();

		myDbHelper.onCreate(db);

		Button login      = null;
		Button registrati = null;

		login      = (Button)   findViewById(R.id.login);
		registrati = (Button)   findViewById(R.id.lblRegistrati);

		user       = (EditText) findViewById(R.id.user);
		pwd        = (EditText) findViewById(R.id.password);

		login.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				User utente             = null;
				UserService userService = new UserService(db);
				try {
					utente = userService.getUserByCdUserAndPwd(user.getText().toString(), pwd.getText().toString());

					if(utente != null){
						Intent intent = new Intent(MainActivity.this,WelcomeActivity.class);
						intent.putExtra("userId", utente.getId());
						startActivity(intent);
					} else {
						Toast.makeText(MainActivity.this, "Credenziali errate", Toast.LENGTH_LONG).show();
					}

				} catch (SQLException e) {

				}
			}
		});

		registrati.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				Intent intent = new Intent(MainActivity.this,RegisterActivity.class);
				startActivity(intent);
			}
		});
	}
}